package com.folioreader.ui.view;

import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;

import com.folioreader.Config;
import com.folioreader.R;
import com.folioreader.util.UiUtil;

public class FolioSearchViewNew extends SearchView {
    private SearchAutoComplete searchAutoComplete;


    public FolioSearchViewNew(Context context) {
        super(context);
    }

    public FolioSearchViewNew(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void init(ComponentName componentName, Config config) {
        SearchManager searchManager = (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE);
        setSearchableInfo(searchManager.getSearchableInfo(componentName));
        setIconified(false);
        adjustLayout();
        applyTheme(config);

    }

    private void adjustLayout() {
        View searchMagIcon = findViewById(R.id.search_mag_icon);
        searchMagIcon.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        View searchEditFrame = findViewById(R.id.search_edit_frame);
        ((MarginLayoutParams) (searchEditFrame.getLayoutParams())).leftMargin = 0;
    }

    private void applyTheme(Config config) {
        ImageView searchCloseButton = findViewById(R.id.search_close_btn);
        UiUtil.setColorIntToDrawable(config.getThemeColor(), searchCloseButton.getDrawable());
        searchAutoComplete = findViewById(R.id.search_src_text);
        UiUtil.setEditTextCursorColor(searchAutoComplete, config.getThemeColor());
        UiUtil.setEditTextHandleColor(searchAutoComplete, config.getThemeColor());
        searchAutoComplete.setHighlightColor(ColorUtils.setAlphaComponent(config.getThemeColor(), 85));
        if (config.isNightMode()) {
            searchAutoComplete.setTextColor(ContextCompat.getColor(getContext(), R.color.night_title_text_color));
            searchAutoComplete.setHintTextColor(ContextCompat.getColor(getContext(), R.color.night_text_color));
        } else {
            searchAutoComplete.setHintTextColor(ContextCompat.getColor(getContext(), R.color.edit_text_hint_color));
        }
    }

    public void setDayMode() {
        searchAutoComplete.setTextColor(ContextCompat.getColor(getContext(), R.color.black));
    }

    public void setNightMode() {
        searchAutoComplete.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
    }

}
